package com.joelemon.mockinfluxdbdata.utils;

import com.joelemon.mockinfluxdbdata.common.SystemException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @Description: TODO
 * @Author: HJY
 * @Date: 2023/11/16
 */
@Slf4j
@Component
public class OkHttpUtil {

    private static OkHttpClient okHttpClient = new OkHttpClient();

//    @Autowired
//    public OkHttpUtil(OkHttpClient okHttpClient) {
//        OkHttpUtil.okHttpClient = okHttpClient;
//    }

    public static final String JSON = "application/json; charset=utf-8";
    public static final String XML = "application/xml; charset=utf-8";
    public static final String TEXT = "application/text; charset=utf-8";

    /**
     * get
     *
     * @param url   请求的url
     * @param param 请求的参数
     * @return
     */
    public static String get(String url, Map<String, String> param) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);
        if (param != null && param.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = param.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request.Builder()
                .url(sb.toString())
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * post
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     * @return
     */
    public static String post(String url, Map<String, String> params) {
        String responseBody = "";
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * get
     *
     * @param url   请求的url
     * @param param 请求的参数
     * @return
     */
    public static String getForHeader(String url, Map<String, String> param) {
        String responseBody = "";
        StringBuffer sb = new StringBuffer(url);
        if (param != null && param.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = param.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?" + entry.getKey() + "=" + entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&" + entry.getKey() + "=" + entry.getValue());
                }
            }
        }
        Request request = new Request.Builder()
                .addHeader("key", "value")
                .url(sb.toString())
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return responseBody;
    }

    /**
     * Post请求发送JSON数据
     *
     * @param url     请求Url
     * @param content 请求的JSON
     */
    public static <T> T postRawParams(String url, String content, String charset,
                                      Predicate<Integer> responseCode,
                                      Function<String, T> converter) throws SystemException {
        RequestBody requestBody = RequestBody.create(MediaType.parse(charset), content);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (responseCode.test(status)) {
                return converter.apply(response.body().string());
            } else {
                log.error("okhttp3 post failed：{}", response.body().string());
                throw new SystemException("post failed：" + response.body().string());
            }
        } catch (Exception e) {
            log.error("okhttp3 post exception：{}", e.getMessage());
            throw new SystemException("post failed：" + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

}